<template>
    <div ref="chartRef" class="system-home"></div>
</template>

<script setup>
import { nextTick, onMounted, onUnmounted, ref } from 'vue';
import * as echarts from 'echarts';
import dayjs from 'dayjs';
import { queryEmployees } from '@/api/employee';

// 引用 DOM 元素
const chartRef = ref(null);

// 图表数据
const employeeData = ref([]);
// 季度排序表
const years = ref([]);

const seriesLine = ref([]);

const resultData = (data) => {
    // 提取所有的 create_time 并转换为季度
    let quarters = new Set();
    data.forEach(item => {
        const date = new Date(item.create_time);
        const year = date.getFullYear();
        const quarter = Math.floor(date.getMonth() / 3) + 1;
        quarters.add(`${year}年第${quarter}季度`);
    });

    // 对季度进行排序
    years.value = Array.from(quarters).sort();
    // 初始化结果数组
    let result = [["product", ...years.value]];

    // 提取所有的部门名称
    const departments = new Set();
    data.forEach(item => {
        departments.add(item.department_name);
    });

    // 将部门名称转换为数组并排序
    const sortedDepartments = Array.from(departments).sort((a, b) => a.localeCompare(b));

    // 统计每个部门在每个季度的员工数量
    sortedDepartments.forEach(department => {
        seriesLine.value.push({
            type: 'line',
            smooth: true,
            seriesLayoutBy: 'row',
            emphasis: { focus: 'series' }
        })
        const row = [department];
        years.value.forEach(quarter => {
            const [year, q] = quarter.replace("季度", '').split('年第');
            const quarterEndDate = new Date(year, q * 3, 0);
            const count = data.filter(item => {
                const createDate = new Date(item.create_time);
                return item.department_name === department && createDate <= quarterEndDate;
            }).length;
            row.push(count);
        });
        result.push(row);
    });
    employeeData.value = result;
}

const doChart = () => {
    const myChart = echarts.init(chartRef.value);
    const option = {
        title: {
            text: '职工分布情况',
            textStyle: {
                fontSize: 24,

            },
            top: 50,
            left: 80
        },
        legend: {
            orient: 'vertical',
            top: 50,
            right: 250,
            textStyle: {
                fontSize: 14,
                lineHeight: 16
            }
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                crossStyle: {
                    color: '#999'
                }
            },
            formatter: function (params) {
                let tooltipStr = `<div style="text-align: center; margin-bottom: 5px; font-size: 14px; min-width: 85px">${params[0].axisValueLabel}</div>`;
                params.forEach((param, index) => {
                    tooltipStr += `<div style="color: ${param.color};">${param.seriesName}: <span style="float: right"> ${param.value[index + 1]}人 </span></div>`;
                });
                return tooltipStr;
            },
        },
        dataset: {
            source: employeeData.value
        },
        xAxis: { type: 'category', name: '季度', nameTextStyle: { fontSize: 14 } },
        yAxis: { gridIndex: 0, name: '人数', nameTextStyle: { fontSize: 14 }, axisLine: { show: true } },
        grid: { top: '45%', left: 80, right: 80, bottom: 50 },
        series: [
            ...seriesLine.value,
            {
                type: 'pie',
                id: 'pie',
                radius: '30%',
                center: ['52%', '23%'],
                emphasis: {
                    focus: 'self'
                },
                label: {
                    formatter: `{b}: {@${years.value[years.value.length - 1]}}人 ({d}%)`
                },
                encode: {
                    itemName: 'product',
                    value: `${years.value[years.value.length - 1]}`,
                    tooltip: `${years.value[years.value.length - 1]}`
                }
            }
        ]
    };

    myChart.on('updateAxisPointer', function (event) {
        const xAxisInfo = event.axesInfo[0];
        if (xAxisInfo) {
            const dimension = xAxisInfo.value + 1;
            myChart.setOption({
                series: {
                    id: 'pie',
                    label: {
                        formatter: `{b}: {@${years.value[dimension - 1]}}人 ({d}%)`
                    },
                    encode: {
                        value: years.value[dimension - 1],
                        tooltip: years.value[dimension - 1]
                    }
                }
            });
        }
    });

    myChart.setOption(option);

    window.addEventListener('resize', () => {
        if (myChart) {
            myChart.resize();
        }
    });

    // 销毁图表实例
    onUnmounted(() => {
        if (myChart) {
            myChart.dispose();
        }
    });
}

const getEmployeeData = async () => {
    try {
        const res = await queryEmployees();
        let data = res.data.list;
        resultData(data);
        // 数据更新后调用 doChart
        nextTick(() => {
            doChart();
        });
    } catch (error) {
        console.log("请求失败");
    }
};

onMounted(() => {
    getEmployeeData();
});
</script>

<style lang="scss" scoped>
.system-home {
    width: 100%;
    height: 100%;
}
</style>